package com.yuyu.commons.caffeine;

import com.github.benmanes.caffeine.cache.Cache;
import com.yuyu.commons.exception.BusinessException;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author
 * @version 1.0
 * @description: 本地缓存
 * @date 2022/9/9 11:23
 */
@Component
public class LocalCacheUtil<Q,T> {

    //todo 先查询本地 再查询redis 再查询db
    public T get(Q key,ICallBack<Q,T> callBack,Cache<Q,T> build,Long redisExpire){
        try {
            //先查询本地缓存
            if (Objects.isNull(callBack.getFromCache(build,key))) {
                if (Objects.isNull(callBack.getFromRedis(key))) {
                    return callBack.getFromDB(key,redisExpire);
                }else {
                    T fromRedis = callBack.getFromRedis(key);
                    build.put(key,fromRedis);
                    return build.getIfPresent(key);
                }
            }else {
                return callBack.getFromCache(build,key);
            }
        }catch (Exception e){
            throw new BusinessException(e.getMessage());
        }
    }

   }

